package com.archeanx.libx.util

import android.media.MediaPlayer
import android.view.ViewGroup
import android.widget.VideoView

/**
 * videoview 预览处理，根据屏幕和视频大小，适配
 */
fun VideoView.onPrepared(
    listener: OnPreparedCompleteListener? = null
) {
    this.setOnPreparedListener(object : MediaPlayer.OnPreparedListener {
        private var mShowWdith = 0
        private var mShowHeight = 0
        override fun onPrepared(mp: MediaPlayer) {
            post {
                val videoWidth = mp.videoWidth
                val videoHeight = mp.videoHeight

                val targetWdith = (parent as ViewGroup).width
                val targetHeight = (parent as ViewGroup).height

                when {
                    videoHeight > targetHeight -> {
                        //当视频高度大于屏幕高度，应缩小视频
                        mShowHeight = targetHeight
                        mShowWdith = (videoWidth.toFloat() / videoHeight * targetHeight).toInt()
                    }
                    videoWidth > targetWdith -> {
                        //当视频宽度大于屏幕宽度，应缩小视频
                        mShowWdith = targetWdith
                        mShowHeight = (videoHeight.toFloat() / videoWidth * targetWdith).toInt()
                    }
                    else -> {
                        //当视频处于屏幕内的时候，需要把videoview 缩小到视频大小
                        //若视频最大 边小于屏幕， 则需要放大视频
                        if (videoWidth > videoHeight) {
                            mShowWdith = targetWdith
                            mShowHeight = (targetWdith.toFloat() / videoWidth * videoHeight).toInt()
                        } else {
                            mShowWdith = (targetHeight.toFloat() / videoHeight * videoWidth).toInt()
                            mShowHeight = targetHeight
                        }
                    }
                }
                val layoutParams = layoutParams
                layoutParams.width = mShowWdith
                layoutParams.height = mShowHeight
                setLayoutParams(layoutParams)
                post {
                    mp.start()
                    listener?.onPrepared()
                }
            }
        }
    })
}

interface OnPreparedCompleteListener {
    fun onPrepared()
}
